<template>
	<view class="content">
		<view class="navbar">
			<view v-for="(item, index) in navList" :key="index" class="nav-item"
				:class="{current: tabCurrentIndex === index}" @click="tabClick(item.state)">
				{{item.text}}
			</view>
		</view>
		<!-- <div v-for="order in orderList" :key="order.id">
				      {{ order.addTime }}
				    </div> -->

		<swiper :current="tabCurrentIndex" class="swiper-box" duration="300" @change="changeTab">
			<swiper-item class="tab-content" v-for="(tabItem,tabIndex) in navList" :key="tabIndex">
				<scroll-view class="list-scroll-content" scroll-y @scrolltolower="loadData">
					<!-- 空白页 -->
					<empty v-if="tabItem.loaded === true && tabItem.orderList.length === 0"></empty>

					<!-- 订单列表 -->
					<view v-for="(item,index) in orderList" :key="index" class="order-item" ><!--@click="viewOrderDetail(item)"-->
						<view class="i-top b-b">
							<text class="time">订单编号：{{item.orderSn}}</text>
							<text class="state"
								:style="{color: item.stateTipColor}">{{item.dtsorderStatus.orderStatusName}}</text>
							<text v-if="item.state===9" class="del-btn yticon icon-iconfontshanchu1"
								@click="deleteOrder(index)"></text>
						</view>

						<!-- 新增商品展示部分 -->
						<view class="goodsview" @click="viewOrderDetail(item)">
							<view v-for="(goodsItem, goodsIndex) in item.orderGoodsList" :key="goodsIndex"
								class="goods-item">
								<image class="goods-img" :src="goodsItem.picUrl" mode="aspectFill"
									style="width: 100px; height: 100px;"></image>
								<view class="goods-info">
									<text class="goods-name">{{goodsItem.goodsName}}</text>
									<text class="goods-specifications">{{goodsItem.specifications}}</text>
									<view class="price-and-num">
										<text class="goods-price">￥{{goodsItem.price}}</text>
										<text class="goods-attr">共 {{goodsItem.number}} 件商品</text>
									</view>
								</view>
							</view>
						</view>

						<view class="price-box">
							实付款
							<text class="price">{{item.actualPrice}}</text>
						</view>
						<!-- 按钮区域（关键修改部分） -->
						<view class="action-box b-t">
							<!-- 待付款状态 -->
							<template v-if="item.dtsorderStatus.orderStatusID === 101">
								<button class="action-btn" @click.stop="cancelOrder(item)">取消订单</button>
								<button class="action-btn recom" @click="viewOrderDetail(item)">
									立即支付
								</button>
							</template>

							<!-- 已取消状态（显示删除按钮） -->
							<template v-if="[102, 103].includes(item.dtsorderStatus.orderStatusID)">
								<button class="action-btn recom" @click.stop="confirmDelete(item)">删除订单</button>
							</template>

							<!-- 待发货/待收货 -->
							<template v-else-if="[201, 301].includes(item.dtsorderStatus.orderStatusID)">
								<button class="action-btn" @click.stop="applyRefund(item)">申请退款</button>
								<!-- 新增确认收货按钮 -->
								<button v-if="item.dtsorderStatus.orderStatusID === 301" class="action-btn recom"
									@click.stop="confirmReceipt(item)">
									确认收货
								</button>
							</template>

							<!-- 待评价 -->
							<button v-else-if="item.dtsorderStatus.orderStatusID === 401" class="action-btn recom"
								@click="evaluateOrder(item)">
								立即评价
							</button>
						</view>
					</view>

					<uni-load-more :status="tabItem.loadingType"></uni-load-more>

				</scroll-view>
			</swiper-item>
		</swiper>
	</view>
</template>

<style>
	.goodsview {
		margin-top: 10px;
	}

	.goods-info {
		width: 250px;
		float: right;
		margin-right: 15px;
	}

	.goods-name {
		font-size: 15px;
		width: 240px;
		display: inline-block;
	}

	.goods-specifications {
		font-size: 12px;
		display: inline-block;
		margin-top: 6px;
		color: #999;
	}

	.price-and-num {
		display: inline-block;
		margin-top: 10px;
		font-size: 15px;
		width: 240px;
	}

	.goods-attr {
		float: right;
	}
</style>

<script>
	import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue';
	import { mapState } from 'vuex';
	import empty from "@/components/empty";
	import Json from '@/Json';
	import {
		getOrder,
		getQuOrder,
		getDelOrder
	} from '@/config/api/order.js';
	import { returnCouponApi } from '@/config/api/coupon.js';
	export default {
		components: {
			uniLoadMore,
			empty
		},
		computed: {
		    ...mapState(['userInfo'])
		  },
		data() {
			return {
				tabCurrentIndex: 0,
				navList: [{
						state: 0,
						text: '全部',
						loadingType: 'more',

					},
					{
						state: 101,
						text: '待付款',
						loadingType: 'more',

					},
					{
						state: 201,
						text: '待发货',
						loadingType: 'more',

					},
					{
						state: 301,
						text: '待收货',
						loadingType: 'more',

					},
					{
						state: 401,
						text: '待评价',
						loadingType: 'more',

					}
				],
				orderList: {

				},

			};
		},

		onLoad(options) {
			/**
			 * 修复app端点击除全部订单外的按钮进入时不加载数据的问题
			 * 替换onLoad下代码即可
			 */
			this.tabCurrentIndex = +options.state;
			// #ifndef MP
			this.loadData()
			// #endif
			// #ifdef MP
			if (options.state == 0) {
				this.loadData()
			}
			// #endif

		},
		mounted() {
			this.loadOrders()
		},
		onShow() {
			this.loadOrders(); // 页面显示时重新加载订单
		},


		methods: {
			// 申请退款
			applyRefund(item) {
				const itemArray = [item];
				uni.navigateTo({
					url: `/pages/order/RefundOrder?item=${JSON.stringify(itemArray)}`,
				});
			},

			evaluateOrder(item) {
				const itemArray = [item];
				uni.navigateTo({
					url: `/pages/user/comment?item=${JSON.stringify(itemArray)}`,
				});
			},
			confirmReceipt(item) {
				uni.showModal({
					title: '确认收货',
					content: '请确认您已收到商品？',
					success: async (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '处理中...'
							});
							const dtsOrder = {
								id: item.id,
								orderStatus: 401
							}
							try {
								// 调用确认收货接口
								await getQuOrder(
									dtsOrder // 假设401是确认收货后的状态
								);

								// 刷新订单列表
								this.loadOrders();
								uni.showToast({
									title: '确认成功',
									icon: 'success'
								});
							} catch (error) {
								console.error('确认失败:', error);
								uni.showToast({
									title: '操作失败',
									icon: 'none'
								});
							}
						}
					}
				});
			},
			/***********/
			  //将数据传到deailOrder页面中
			viewOrderDetail(item) {
			    const params = encodeURIComponent(JSON.stringify(item));
			    uni.navigateTo({
			      url: `/pages/order/deailOrder?order=${params}`
			    });
			  },
			
			
			//获取订单列表
			async loadOrders() {
				try {
					const userId = this.userInfo.id;
					const orderStatus = this.tabCurrentIndex;
					const res = await getOrder({
						userId,
						orderStatus
					})
					if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code ===
						200) {
						this.orderList = res.data.data
					} else {
						console.error('请求失败:', res?.data?.msg || '未知错误');
					}
				} catch (error) {
					console.error('接口异常:', error)
					this.$message.error('数据加载失败')
				}
			},



			loadData(source) {
				//这里是将订单挂载到tab列表下
				let index = this.tabCurrentIndex;
				let navItem = this.navList[index];
				let state = navItem.state;

				if (source === 'tabChange' && navItem.loaded === true) {
					//tab切换只有第一次需要加载数据
					return;
				}
				if (navItem.loadingType === 'loading') {
					//防止重复加载
					return;
				}

				navItem.loadingType = 'loading';

				// setTimeout(() => {
				// 	let orderList = Json.orderList.filter(item => {
				// 		//添加不同状态下订单的表现形式
				// 		item = Object.assign(item, this.orderStateExp(item.state));
				// 		//演示数据所以自己进行状态筛选
				// 		if (state === 0) {
				// 			//0为全部订单
				// 			return item;
				// 		}
				// 		return item.state === state
				// 	});
				// 	orderList.forEach(item => {
				// 		navItem.orderList.push(item);
				// 	})
				// 	//loaded新字段用于表示数据加载完毕，如果为空可以显示空白页
				// 	this.$set(navItem, 'loaded', true);

				// 	//判断是否还有数据， 有改为 more， 没有改为noMore 
				// 	navItem.loadingType = 'more';
				// }, 600);
			},

			//swiper 切换
			changeTab(e) {
				this.tabCurrentIndex = e.target.current;
				this.orderList = [];
				this.loadData('tabChange');
			},

			//顶部tab点击
			tabClick(state) {
				this.tabCurrentIndex = state;
				this.loadOrders();
			},

			//删除订单
			confirmDelete(item) {
				uni.showModal({
					title: '删除订单',
					content: '确认要永久删除该订单吗？',
					success: async (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '处理中...'
							});
							try {
								// 调用真实删除接口
								await getDelOrder({
									id: item.id
								});

								// 前端列表更新
								const index = this.orderList.findIndex(o => o.id === item.id);
								if (index > -1) {
									this.orderList.splice(index, 1);
								}

								uni.showToast({
									title: '删除成功',
									icon: 'success'
								});
							} catch (error) {
								console.error('删除失败:', error);
								uni.showToast({
									title: '删除失败',
									icon: 'none'
								});
							}
						}
					}
				});
			},
			//取消订单
			async cancelOrder(item) {
				const dtsOrder = {
					id: item.id,
					orderStatus: 102
				}
				try {
					console.log(dtsOrder);
					const res = await getQuOrder(dtsOrder)
					if (res && res.data && typeof res.data === 'object' && 'code' in res.data && res.data.code ===
						200) {
						console.log("成功!");
						this.loadOrders();
					} else {
						console.error('请求失败:', res?.data?.msg || '未知错误');
					}
				} catch (error) {
					console.error('接口异常:', error)
					this.$message.error('数据加载失败')
				}
				//如果有优惠卷取消订单后，就将他还给用户
				if (item.couponPrice != 0){
					const dtsCouponUser = {
						userId : item.userId,
						orderSn : item.orderSn
					}
					try {
						const returnRes = await returnCouponApi(dtsCouponUser)
						if (returnRes && returnRes.data && typeof returnRes.data === 'object' && 'code' in returnRes.data && returnRes.data.code ===
							200) {
							console.log("成功!");
						} else {
							console.error('请求失败:', returnRes?.data?.msg || '未知错误');
						}
					} catch (error) {
						console.error('接口异常:', error)
						this.$message.error('数据加载失败')
					}
					
				}
				
			},

			//订单状态文字和颜色
			orderStateExp(state) {
				let stateTip = '',
					stateTipColor = '#fa436a';
				switch (+state) {
					case 1:
						stateTip = '待付款';
						break;
					case 2:
						stateTip = '待发货';
						break;
					case 9:
						stateTip = '订单已关闭';
						stateTipColor = '#909399';
						break;

						//更多自定义
				}
				return {
					stateTip,
					stateTipColor
				};
			}
		},
	}
</script>

<style lang="scss">
	page,
	.content {
		background: $page-color-base;
		height: 100%;
	}

	.swiper-box {
		height: calc(100% - 40px);
	}

	.list-scroll-content {
		height: 100%;
	}

	.navbar {
		display: flex;
		height: 40px;
		padding: 0 5px;
		background: #fff;
		box-shadow: 0 1px 5px rgba(0, 0, 0, .06);
		position: relative;
		z-index: 10;

		.nav-item {
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100%;
			font-size: 15px;
			color: $font-color-dark;
			position: relative;

			&.current {
				color: $base-color;

				&:after {
					content: '';
					position: absolute;
					left: 50%;
					bottom: 0;
					transform: translateX(-50%);
					width: 44px;
					height: 0;
					border-bottom: 2px solid $base-color;
				}
			}
		}
	}

	.uni-swiper-item {
		height: auto;
	}

	.order-item {
		display: flex;
		flex-direction: column;
		padding-left: 30upx;
		background: #fff;
		margin-top: 16upx;

		.i-top {
			display: flex;
			align-items: center;
			height: 80upx;
			padding-right: 30upx;
			font-size: $font-base;
			color: $font-color-dark;
			position: relative;

			.time {
				flex: 1;
			}

			.state {
				color: $base-color;
			}

			.del-btn {
				padding: 10upx 0 10upx 36upx;
				font-size: $font-lg;
				color: $font-color-light;
				position: relative;

				&:after {
					content: '';
					width: 0;
					height: 30upx;
					border-left: 1px solid $border-color-dark;
					position: absolute;
					left: 20upx;
					top: 50%;
					transform: translateY(-50%);
				}
			}
		}

		/* 多条商品 */
		.goods-box {
			height: 160upx;
			padding: 20upx 0;
			white-space: nowrap;

			.goods-item {
				width: 120upx;
				height: 120upx;
				display: inline-block;
				margin-right: 24upx;
			}

			.goods-img {
				display: block;
				width: 100%;
				height: 100%;
			}
		}

		/* 单条商品 */
		.goods-box-single {
			display: flex;
			padding: 20upx 0;

			.goods-img {
				display: block;
				width: 120upx;
				height: 120upx;
			}

			.right {
				flex: 1;
				display: flex;
				flex-direction: column;
				padding: 0 30upx 0 24upx;
				overflow: hidden;

				.title {
					font-size: $font-base + 2upx;
					color: $font-color-dark;
					line-height: 1;
				}

				.attr-box {
					font-size: $font-sm + 2upx;
					color: $font-color-light;
					padding: 10upx 12upx;
				}

				.price {
					font-size: $font-base + 2upx;
					color: $font-color-dark;

					&:before {
						content: '￥';
						font-size: $font-sm;
						margin: 0 2upx 0 8upx;
					}
				}
			}
		}

		.price-box {
			display: flex;
			justify-content: flex-end;
			align-items: baseline;
			padding: 20upx 30upx;
			font-size: $font-sm + 2upx;
			color: $font-color-light;

			.num {
				margin: 0 8upx;
				color: $font-color-dark;
			}

			.price {
				font-size: $font-lg;
				color: $font-color-dark;

				&:before {
					content: '￥';
					font-size: $font-sm;
					margin: 0 2upx 0 8upx;
				}
			}
		}



	}

	/* 关键样式调整 */
	.action-box {
		display: flex;
		justify-content: flex-end;
		margin-bottom: 20px;
		padding-left: 210px;
	}

	.action-btn {
		height: 60rpx;
		line-height: 60rpx;
		min-width: 160rpx;
		padding: 0 30rpx;
		font-size: 26rpx;
		border: 1rpx solid #ddd;
		border-radius: 40rpx;
		background: #fff;
	}

	.action-btn.recom {
		background: #e54d42;
		color: #fff;
		border-color: #e54d42;
	}

	/* load-more */
	.uni-load-more {
		display: flex;
		flex-direction: row;
		height: 80upx;
		align-items: center;
		justify-content: center
	}

	.uni-load-more__text {
		font-size: 28upx;
		color: #999
	}

	.uni-load-more__img {
		height: 24px;
		width: 24px;
		margin-right: 10px
	}

	.uni-load-more__img>view {
		position: absolute
	}

	.uni-load-more__img>view view {
		width: 6px;
		height: 2px;
		border-top-left-radius: 1px;
		border-bottom-left-radius: 1px;
		background: #999;
		position: absolute;
		opacity: .2;
		transform-origin: 50%;
		animation: load 1.56s ease infinite
	}

	.uni-load-more__img>view view:nth-child(1) {
		transform: rotate(90deg);
		top: 2px;
		left: 9px
	}

	.uni-load-more__img>view view:nth-child(2) {
		transform: rotate(180deg);
		top: 11px;
		right: 0
	}

	.uni-load-more__img>view view:nth-child(3) {
		transform: rotate(270deg);
		bottom: 2px;
		left: 9px
	}

	.uni-load-more__img>view view:nth-child(4) {
		top: 11px;
		left: 0
	}

	.load1,
	.load2,
	.load3 {
		height: 24px;
		width: 24px
	}

	.load2 {
		transform: rotate(30deg)
	}

	.load3 {
		transform: rotate(60deg)
	}

	.load1 view:nth-child(1) {
		animation-delay: 0s
	}

	.load2 view:nth-child(1) {
		animation-delay: .13s
	}

	.load3 view:nth-child(1) {
		animation-delay: .26s
	}

	.load1 view:nth-child(2) {
		animation-delay: .39s
	}

	.load2 view:nth-child(2) {
		animation-delay: .52s
	}

	.load3 view:nth-child(2) {
		animation-delay: .65s
	}

	.load1 view:nth-child(3) {
		animation-delay: .78s
	}

	.load2 view:nth-child(3) {
		animation-delay: .91s
	}

	.load3 view:nth-child(3) {
		animation-delay: 1.04s
	}

	.load1 view:nth-child(4) {
		animation-delay: 1.17s
	}

	.load2 view:nth-child(4) {
		animation-delay: 1.3s
	}

	.load3 view:nth-child(4) {
		animation-delay: 1.43s
	}

	@-webkit-keyframes load {
		0% {
			opacity: 1
		}

		100% {
			opacity: .2
		}
	}
</style>